package com.settlement.system.controller;

import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.enums.RpaDtSmsEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.common.annotation.LoggerProfile;
import com.settlement.system.model.entity.common.TblRpaDtSmsFilter;
import com.settlement.system.model.param.TblRpaDtSmsFilterRequest;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.ITblRpaDtSmsFilterService;
import com.alibaba.fastjson2.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * RPA钉钉短信过滤配置表 前端控制器
 * @author xiaochuan
 * @since 2021-12-28
 */
@Slf4j
@Api(tags = "RPA钉钉短信过滤配置表",description = "RPA钉钉短信过滤配置表")
@RestController
@RequestMapping("/tblRpaDtSmsFilter")
public class TblRpaDtSmsFilterController extends ExcelController<TblRpaDtSmsFilter> {

    @Resource
    private ITblRpaDtSmsFilterService tblRpaDtSmsFilterService;

    @Override
    public IBaseService init() {
        return tblRpaDtSmsFilterService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblRpaDtSmsFilter.class;
    }

    @ApiOperation("createAndGetOneRow")
    @RequestMapping(value = "createAndGetOneRow", method = {RequestMethod.POST})
    public ObjectDataResponse<TblRpaDtSmsFilter> createAndGetOneRow(@RequestBody Map<String, Object> model) {
        Map<String, Object> result = new HashMap<>(16);
        TblRpaDtSmsFilter tblRpaDtSmsFilter = new TblRpaDtSmsFilter();
        try {
            setDefualt(tblRpaDtSmsFilter);
            tblRpaDtSmsFilter.setInUse(RpaDtSmsEnum.InUse.YES.getNo());
            tblRpaDtSmsFilter.setVerifyType(RpaDtSmsEnum.VerifyType.BLACKNAME_MOBILE.getNo());
            tblRpaDtSmsFilterService.insert(tblRpaDtSmsFilter);
        } catch (Exception ex) {
            log.error("createAndGetOneRow出错", ex);
            return new ObjectDataResponse(500, "createAndGetOneRow error，请联系管理员！");
        }
        return new ObjectDataResponse<>(tblRpaDtSmsFilter, 200, "createAndGetOneRow成功");
    }

    @ApiOperation(value = "check")
    @LoggerProfile(methodNote="check")
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public ObjectDataResponse check(@RequestBody TblRpaDtSmsFilterRequest model) {
        try {
            String message = model.verifyBean();
            if (!StringUtils.isEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }

            try{
                BeanMap beanMap = new BeanMap(model);
                TblRpaDtSmsFilter beanModel =
                        JSON.parseObject(JSON.toJSONString(beanMap), TblRpaDtSmsFilter.class);

                message = checkExist(beanModel);
                if(StringUtils.isNotEmpty(message)){
                    return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
                }
            }catch (Exception ex){
                log.info("更新异常",ex);
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(),
                        ReturnStatusEnum.REQUEST_ABNORMAL.getText());
            }

        } catch (Exception ex) {
            log.error("check error", ex);
            return new ObjectDataResponse(500, "服务器异常");
        }
        return new ObjectDataResponse(200, "success");
    }

    @Override
    protected ObjectDataResponse update(@RequestBody TblRpaDtSmsFilter model, HttpServletRequest request) throws ServiceException {

        BeanMap beanMap = new BeanMap(model);
        TblRpaDtSmsFilterRequest beanModel =
                JSON.parseObject(JSON.toJSONString(beanMap), TblRpaDtSmsFilterRequest.class);

        String message = beanModel.verifyBean();
        if (!StringUtils.isEmpty(message)) {
            return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
        }
        try{
            message = checkExist(model);
            if(StringUtils.isNotEmpty(message)){
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }
        }catch (Exception ex){
            log.info("更新异常",ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(),
                    ReturnStatusEnum.REQUEST_ABNORMAL.getText());
        }

        if(StringUtils.isEmpty(model.getParentId())){
            model.setSaveOrNot(1);
        }
        return super.update(model, request);
    }

    public String checkExist(TblRpaDtSmsFilter tblRpaDtSmsFilter) throws ServiceException {
        if(StringUtils.isEmpty(tblRpaDtSmsFilter.getParentId())){
            Map<String,Object> map = new HashMap();
            map.put("robotAccessKey",tblRpaDtSmsFilter.getRobotAccessKey());
            List<TblRpaDtSmsFilter> list = tblRpaDtSmsFilterService.selectByParam(map);
            if(!list.isEmpty()){
                for(TblRpaDtSmsFilter rpaDtSmsFilter:list){
                    if(tblRpaDtSmsFilter.getRobotAccessKey().equals(rpaDtSmsFilter.getRobotAccessKey())
                    && !tblRpaDtSmsFilter.getId().equals(rpaDtSmsFilter.getId())
                    ){
                        log.info("钉钉机器人token已存在:"+rpaDtSmsFilter.getRobotAccessKey());
                        return "钉钉机器人token已存在:"+rpaDtSmsFilter.getRobotAccessKey();
                    }
                }
            }
        }else{
            Map<String,Object> map = new HashMap();
            map.put("parentId",tblRpaDtSmsFilter.getParentId());
            String verifyType = tblRpaDtSmsFilter.getVerifyType();
            map.put("verifyType",verifyType);
            List<TblRpaDtSmsFilter> list = tblRpaDtSmsFilterService.selectByParam(map);
            if(!list.isEmpty()){
                for(TblRpaDtSmsFilter rpaDtSmsFilter:list){
                    if(RpaDtSmsEnum.VerifyType.BLACKNAME_MOBILE.getNo().equals(verifyType) ||
                            RpaDtSmsEnum.VerifyType.WHITENAME_MOBILE.getNo().equals(verifyType)){
                        if(tblRpaDtSmsFilter.getMobile().equals(rpaDtSmsFilter.getMobile())
                                && !rpaDtSmsFilter.getId().equals(tblRpaDtSmsFilter.getId())
                        ){
                            log.info("手机号已存在:"+rpaDtSmsFilter.getMobile());
                            return "手机号已存在:"+rpaDtSmsFilter.getMobile();
                        }
                    }else if(RpaDtSmsEnum.VerifyType.BLACKNAME_KEYWORD.getNo().equals(verifyType)){
                        if(tblRpaDtSmsFilter.getBlacknameKeyword().equals(rpaDtSmsFilter.getBlacknameKeyword())
                                && !rpaDtSmsFilter.getId().equals(tblRpaDtSmsFilter.getId())
                        ){
                            log.info("黑名单关键字已存在:"+rpaDtSmsFilter.getBlacknameKeyword());
                            return "黑名单关键字已存在:"+rpaDtSmsFilter.getBlacknameKeyword();
                        }
                    }
                }
            }

        }
        return null;
    }

    @Override
    protected ObjectDataResponse batchDelete(@RequestBody List<TblRpaDtSmsFilter> deleteList, HttpServletRequest request) throws ServiceException {
        try{
            String message = checkDeleteList(deleteList);
            if (StringUtils.isNotEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }
        } catch (Exception ex) {
            log.error("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
        return super.batchDelete(deleteList, request);
    }

    String checkDeleteList(List<TblRpaDtSmsFilter> deleteList) throws ServiceException {
        for(TblRpaDtSmsFilter tblRpaDtSmsFilter : deleteList){
            Map<String,Object> map = new HashMap();
            map.put("parentId",tblRpaDtSmsFilter.getId());

            List<TblRpaDtSmsFilter> objects = tblRpaDtSmsFilterService.selectByParam(map);
            if(!objects.isEmpty()){
                map = new HashMap();
                map.put("id",tblRpaDtSmsFilter.getId());
                List<TblRpaDtSmsFilter> objects2 = tblRpaDtSmsFilterService.selectByParam(map);
                TblRpaDtSmsFilter rpaDtSmsFilter = objects2.get(0);
                log.info("请先删除短信群 "+rpaDtSmsFilter.getGroupName()+" 的规则信息");
                return "请先删除短信群 "+rpaDtSmsFilter.getGroupName()+" 的规则信息";
            }
        }
        return null;
    }

    @Override
    protected ObjectDataResponse delete(@RequestBody TblRpaDtSmsFilter model, HttpServletRequest request) throws ServiceException {
        try {
            List<TblRpaDtSmsFilter> list = new ArrayList<>();
            list.add(model);
            String message = checkDeleteList(list);
            if (StringUtils.isNotEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("删除数据异常", ex);
            return new ObjectDataResponse(500, "删除失败，请联系管理员！");
        }
        return super.delete(model, request);
    }
}

